<?php
/**
 * 前台主控控制器
 */

namespace Home\Controller;

use Common\Api\ConfigApi;
use Home\Model\HomeModel;
use Think\Controller;
use Addons\WeChatApi\WeChatUser;

class HomeController extends Controller
{
    private $_M;//模型
    private $_openId;//微信的openid
    private $_WechatResData;//微信返回的用户数据

    public function __construct()
    {



        parent::__construct();
        $this->_M = new HomeModel('user');

        /* 读取站点配置 */
        $config = ConfigApi::getConfiglists();
        C($config); //添加配置
        if (!C('WEB_SITE_CLOSE')) {
            $this->error('站点已经关闭，请稍后访问~');
        }

        if(C('CLEAR_SESSION')){
            session(null);
            cookie(null);
        }


        //首页css状态更换
        $this->_changeCssStatus();

        //执行微信相关逻辑
        $this->_doWeChat();


        if (C('HOME_DEBUG')) {
            echo "session:";
            dump(session());
            echo "cookie:";
            dump(cookie());

        }


    }


    /* 空操作，用于输出404页面 */
    public function _empty()
    {
        $this->not_find();
    }


    /**
     * 成功跳转页面
     * @param $msg
     */
    protected function ok($msg)
    {
        $this->assign("msg", $msg);
        $this->display('/Base/ok');
    }

    /**
     * 没有这个页面跳转页面
     */
    protected function not_find()
    {
        $this->display('/Base/not_find');
    }


    /**
     * 页面错误跳转页面
     * @param $msg
     * @param string $msgDetail
     * @param string $url
     */
    protected function err($msg, $msgDetail = '', $url = "")
    {
        $this->assign("msg", $msg);
        $this->assign("msgDetail", $msgDetail);
        $this->assign("url", $url);
        $this->display('/Base/err');
        exit;
    }

    /**
     * 处理首页导航css问题
     */
    private function _changeCssStatus()
    {
        $indexController = array(
            'Index', 'Order', 'PreOrder',
        );
        $serverController = array(
            'Server'
        );

        $userController = array(
            'User'
        );

        $myTicketController = array(
            'MyTicket'
        );

        $controller = trim(CONTROLLER_NAME);
        if (in_array($controller, $indexController)) {
            $this->assign("nav1", 2);
            $this->assign("col1", "mycolor");

        }
        if (in_array($controller, $serverController)) {
            $this->assign("nav2", 2);
            $this->assign("col2", "mycolor");
        }

        if (in_array($controller, $myTicketController)) {
            $this->assign("nav3", 2);
            $this->assign("col3", "mycolor");
        }

        if (in_array($controller, $userController)) {

            $this->assign("nav4", 2);
            $this->assign("col4", "mycolor");
        }
    }


    /**
     * 执行微信相关工作
     */
    private function _doWeChat()
    {

        if(C('IS_UI_DEBUG')){
            session('userId',89);
        }
        $indexSign = I('get.state');//微信跳转过来时携带的state参数

        //验证是否是首次从微信进入
        if ($indexSign == C('FIRST_SIGN')) {
            //是首次从微信进入

            $this->initWechatRes();//初始化微信信息
            if (!empty($this->_openId)) {

                //检查用户是否存在
                if ($userId = $this->_M->checkUserIsExist($this->_openId)) {
                    //存在
                    session('userId', $userId);
                } else {
                    //不存在
                    $userId = $this->addUser();//用户id
                    if ($userId > 0) {
                        session('userId', $userId);
                    } else {
                        $this->err('服务器繁忙,请稍后再试!(添加用户信息失败)');
                        exit;
                    }

                }
            } else {
                if (empty(session('userId'))) {
                    $this->err('系统异常,请稍后再试(获取OPENID错误)');
                    exit;
                }

                //todo 从微信进入全部检测通过
                return;
            }
        } else {
            //不是从微信进入
            if (C('IS_WECHAT_VISIT')) {
                if (empty(session('userId'))) {//直接没有经过微信进入
                    $this->err('请在微信客户端打开');
                    exit;
                }
            }

        }


    }

    /**
     * 获取微信返回的信息
     * @return array
     */
    private function getWechatResData()
    {
        return $this->_WechatResData;
    }


    /**
     * 初始化微信返回来的用户信息
     */
    private function initWechatRes()
    {
        $appid = C('APP_ID');
        $secret = C("APP_SECRET");
        $userObject = new WeChatUser($appid, $secret);
        $wechatRes = $userObject->getUserInfo();
        $this->_openId = $wechatRes['openid'];
        $this->_WechatResData = $wechatRes;
        if (C('HOME_DEBUG')) {
            echo "用户信息:";
            dump($wechatRes);
        }
    }

    /**
     * 新增用户
     * @return int 新增用户的id
     */
    private function addUser()
    {
        $wechatRes = $this->getWechatResData();
        $dbData = array(
            'usr_create_time'=>time(),
            'usr_open_id' => $wechatRes['openid'],
            'usr_sex' => $wechatRes['sex'],
            'usr_title' => $wechatRes['nickname'],
            'usr_addr' => $wechatRes['country'] . $wechatRes['province'] . $wechatRes['city'],
            'usr_headimg_url' => $wechatRes['headimgurl']
        );
        $userId = $this->_M->add($dbData);
        return $userId;
    }

}